﻿/**
作者：
 */
package com.zito.pojo;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.downlove.cache.CacheManager;
import com.downlove.database.DBException;
import com.downlove.database.POJO;
import com.downlove.database.QueryHelper;

public class ColumnzPOJO extends POJO {

	private Long _parentid = -1L;
	private int _orders = 0;
	private String _parentlist = "-1";
	private int _deep;
	private int _child;
	private String _columnname;

	private Object[] valueObj;

	public void setParentid(Long parentid) {
		this._parentid = parentid;
	}

	public Long getParentid() {
		return _parentid;
	}

	public void setOrders(int orders) {
		this._orders = orders;
	}

	public int getOrders() {
		return _orders;
	}

	public void setParentlist(String parentlist) {
		this._parentlist = parentlist;
	}

	public String getParentlist() {
		return _parentlist;
	}

	public int getDeep() {
		return _deep;
	}

	public void setDeep(int deep) {
		this._deep = deep;
	}

	public int getChild() {
		return _child;
	}

	public void setChild(int child) {
		this._child = child;
	}

	public void setColumnname(String columnname) {
		this._columnname = columnname;
	}

	public String getColumnname() {
		return _columnname;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public List<? extends POJO> allList() {
		String sql = "SELECT id FROM " + TableName() + " ORDER BY orders";
		List<Long> tmpList = QueryHelper.queryList(sql, 1, TotalCount());
		return this.LoadList(tmpList);
	}

	public long Save() {
		String upOrder = "UPDATE " + TableName()
				+ " SET orders=orders+1 WHERE orders > ?";
		String maxOrders = "SELECT MAX(orders) FROM " + TableName();
		String updateParentChild = "UPDATE " + TableName()
				+ " SET child=child+1 WHERE id=?";
		int tempOrders = 1;
		int tempDeep = -1;

		if (this.getParentid() == -1) {
			Object tmpObj = QueryHelper.query(maxOrders);
			tempOrders = (tmpObj == null) ? 1 : (Integer) tmpObj;
		} else {
			ColumnzPOJO _pojo = Get(this.getParentid());
			String filter = _pojo.getParentlist() + "," + _pojo.getId();
			// System.out.println("filter : "+ filter);
			Object tmpObj = QueryHelper.query(maxOrders
					+ " WHERE parentlist like ?", filter + "%");
			tempOrders = (tmpObj == null) ? _pojo.getOrders()
					: (Integer) tmpObj;
			// tempOrders = _pojo.getOrders();
			tempDeep = _pojo.getDeep();
		}
		this.setOrders(tempOrders + 1);
		this.setDeep(tempDeep + 1);
		this.setChild(0);
		// String insertSQL = kSQL(this);
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(upOrder, tempOrders);
			QueryHelper.commitUpdate(_SQL(this), this.valueObj);
			if (this.getParentid() != -1) {
				QueryHelper.commitUpdate(updateParentChild, this.getParentid());
			}
			QueryHelper.commit();
		} catch (Exception e) {
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				throw new DBException(e1);
			}
			throw new DBException(e);
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				throw new DBException(e2);
			}
		}
		if (this.IsObjectCachedByID())
			CacheManager.evict(CacheRegion(), OBJ_COUNT_CACHE_KEY);
		return getId();
	}

	public boolean Delete() {
		if (this.getId() == -1)
			return false;

		String downOrder = "UPDATE " + TableName()
				+ " SET orders=orders-? WHERE orders > ?";
		String deleteSQL = "DELETE FROM " + TableName() + " WHERE id=?";
		String deleteChild = "DELETE FROM " + TableName()
				+ " WHERE parentlist like ?";
		String updateParentChild = "UPDATE " + TableName()
				+ " SET child=child-1 WHERE id=?";
		String getChildSQL = "SELECT COUNT(*) FROM " + TableName()
				+ " WHERE  parentlist like ?";

		ColumnzPOJO _pojo = Get(this.getId());
		ColumnzPOJO _parent = null;
		int _operateOrders = _pojo.getOrders();
		if (_pojo.getParentid() != -1) {
			_parent = Get(_pojo.getParentid());
			_operateOrders = _parent.getOrders();
		}

		int tmpAllChild = 0;

		String filter = _pojo.getParentlist() + "," + _pojo.getId();

		Object tmpObj = QueryHelper.query(getChildSQL, filter + "%");

		tmpAllChild = (tmpObj == null) ? 0 : ((Long) tmpObj).intValue();

		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(deleteSQL, this.getId());
			QueryHelper.commitUpdate(deleteChild, filter + "%");
			if (_parent != null)
				QueryHelper.commitUpdate(updateParentChild, this.getParentid());
			QueryHelper
					.commitUpdate(downOrder, tmpAllChild + 1, _operateOrders);
			QueryHelper.commit();
		} catch (Exception e) {
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				throw new DBException(e1);
			}
			throw new DBException(e);
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				throw new DBException(e2);
			}
		}

		return true;
	}

	public boolean Update() {
		if (getId() == -1)
			return false;
		String SQL = "UPDATE " + TableName()
				+ " SET columnname = ?  WHERE id= ?";
		return QueryHelper.update(SQL, getColumnname(), getId()) == 1 ? true
				: false;
	}

	private String _SQL(ColumnzPOJO obj) {
		Map<String, Object> pojo_bean = obj.ListInsertableFields();
		String[] fields = pojo_bean.keySet().toArray(
				new String[pojo_bean.size()]);
		StringBuilder sql = new StringBuilder("INSERT INTO ");
		sql.append(obj.TableName());
		sql.append('(');
		valueObj = new Object[fields.length];
		for (int i = 0; i < fields.length; i++) {
			if (i > 0)
				sql.append(',');
			sql.append(fields[i]);
		}
		sql.append(") VALUES(");
		for (int i = 0; i < fields.length; i++) {
			if (i > 0)
				sql.append(',');
			sql.append('?');
			valueObj[i] = pojo_bean.get(fields[i]);
		}
		sql.append(')');
		return sql.toString();
	}

	public String inIdList(String list) {
		String sql = "SELECT id as ids FROM " + TableName()
				+ " WHERE parentlist like '" + list + "%'";
		List<Long> tmplist = QueryHelper.queryList(sql);
		StringBuilder string = new StringBuilder("");
		for (int i = 0; i < tmplist.size(); i++){
			if (i > 0)
				string.append(',');
			string.append(tmplist.get(i));
		}
		//System.out.println("string : " + string.toString());
		return string.toString();
	}

}
